package cn.wangzg.restdemo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@RestController
public class LoginController {

    //定义cookie全局变量，供需要携带cookie的接口使用
    Cookie cookie;
    @Autowired
    DataSource dataSource;

    //定义一个login的post方法，然后返回cookie信息
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String Login(HttpServletResponse response,
                        @RequestParam("name") String name,
                        @RequestParam("password") String password){
        String sql ="select count(*) as number from user where name='"+name+"'"+"and password='"+password+"'";
        int num =0;
        try {
            //1.创建连接
            Connection connection = dataSource.getConnection();
            //2.获得一个statement对象，将要执行的sql脚本封装到此对象中
            PreparedStatement statement =connection.prepareStatement(sql);
            ResultSet ResultSet = statement.executeQuery();
            while(ResultSet.next()) {
                num =ResultSet.getInt("number");
            }
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if(num>0){
            cookie=new Cookie("token","1234567890");
            response.addCookie(cookie);
            return "登录成功";
        }
        //如果用户名和密码成功，就添加cookie信息，然后添加到response中，然后成功信息
//        if(name.equals("admin") && password.equals("123456")){
//            cookie=new Cookie("token","1234567890");
//            response.addCookie(cookie);
//            return "返回cookie，登录成功";
//        }

        return "登录失败";
    }
}
